package com.cscec5b.inspection.web;

import com.cscec5b.inspection.controller.UserSyncController.TooManyRequestsException;
import com.cscec5b.inspection.dto.ApiError;
import com.cscec5b.inspection.service.UserSyncService.ConflictException;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiError handleValid(MethodArgumentNotValidException e) {
        return new ApiError("400", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiError handleCv(ConstraintViolationException e) {
        return new ApiError("400", e.getMessage());
    }

    @ExceptionHandler(TooManyRequestsException.class)
    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public ApiError handle429() { return new ApiError("429", "too many requests"); }

    @ExceptionHandler(ConflictException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public ApiError handle409() { return new ApiError("409", "idempotency conflict"); }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiError handle400(IllegalArgumentException e) { return new ApiError("400", e.getMessage()); }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiError handle500(RuntimeException e) { return new ApiError("500", e.getMessage()); }
}
